﻿using System;
using System.IO;
using System.Web;
using Dost.Khcn.Biz;
using Dost.Khcn.Data.EntityModel;

namespace Dost.Khcn.Web.ChuyenGia
{
    /// <summary>
    /// Summary description for FileUpload
    /// </summary>
    public class FileUpload : IHttpHandler
    {
        private static ChuyenGiaFileBiz _chuyenGiaFileBiz;
        private static ChuyenGiaFileBiz ChuyenGiaFileManager
        {
            get { return _chuyenGiaFileBiz ?? (_chuyenGiaFileBiz = new ChuyenGiaFileBiz()); }
        }

        public void ProcessRequest(HttpContext context)
        {
            if (context.Request.HttpMethod == "POST")
            {
                var uploadFile = context.Request["uploadFile"];
                var chuyenGiaId = context.Request["chuyenGiaId"];

                var intChuyenGiaId = 0;
                if (int.TryParse(chuyenGiaId, out intChuyenGiaId))
                {
                    var stream = context.Request.InputStream;
                    if (String.IsNullOrEmpty(context.Request["uploadFile"]))
                    {
                        // IE
                        var postedFile = context.Request.Files[0];
                        stream = postedFile.InputStream;
                    }

                    var buffer = new byte[stream.Length];
                    stream.Read(buffer, 0, buffer.Length);

                    var chuyenGiaFile = new ChuyenGiaFile
                                        {
                                            ChuyenGiaId = intChuyenGiaId,
                                            FileContent = buffer,
                                            CreatedDate = DateTime.Now,
                                            FileName = uploadFile,
                                            FileExtension = Path.GetExtension(uploadFile)
                                        };
                    ChuyenGiaFileManager.Create(chuyenGiaFile);
                }
            }

            context.Response.ContentType = "text/plain";
            context.Response.Write("{\"success\":true}");
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}